package com.mmall.util;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

    private static Logger logger = LoggerFactory.getLogger(CookieUtil.class);
    private final static String COOKIE_DOMAIN = ".tmpan.com";
    private final static String COOKIE_NAME = "mmall_cookie_token";

    /**
     * 写入cookie
     * @param response
     * @param token
     */
    public static void wirteLoginToken(HttpServletResponse response, String token) {
        //名字
        Cookie cookie = new Cookie(COOKIE_NAME, token);
        //作用域
        cookie.setDomain(COOKIE_DOMAIN);
        //路径 (/代表根目录)
        cookie.setPath("/");
        //设置状态
        cookie.setHttpOnly(true);
        //有效期 (-1 永久有效 单位是秒 如果不设置 只会写入内存  不会写入硬盘 只在当前页面有效)
        cookie.setMaxAge(60 * 60 * 24 * 365);
        logger.info("wirteCookieName:{},CookieVal:{}", cookie.getName(), cookie.getValue());
        response.addCookie(cookie);
    }


    /**
     * 读取cookie
     * @param request
     * @return
     */
    public static String readLoginToken(HttpServletRequest request) {
        Cookie[] cks = request.getCookies();
        if (cks != null) {
            for (Cookie cookie : cks) {
                logger.info("cookieName:{},cookieVal:{}", cookie.getName(), cookie.getValue());
                if (StringUtils.equals(cookie.getName(), COOKIE_NAME)) {
                    logger.info("return cookieName:{},cookieVal:{}", cookie.getName(), cookie.getValue());

                    return cookie.getValue();
                }
            }
        }
        return null;
    }


    /**
     * 删除cookie
     * @param request
     * @param response
     */
    public static void delLoginToken(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cks = request.getCookies();

        if (cks != null) {
            for (Cookie cookie : cks) {
                if (StringUtils.equals(cookie.getName(), COOKIE_NAME)) {
                    //作用域
                    cookie.setDomain(COOKIE_DOMAIN);
                    //路径 (/代表根目录)
                    cookie.setPath("/");
                    //有效期 (-1 永久有效 单位是秒 如果不设置 只会写入内存  不会写入硬盘 只在当前页面有效)
                    cookie.setMaxAge(0);//删除该cookie 有效期为零
                    logger.info("return cookieName:{},cookieVal:{}", cookie.getName(), cookie.getValue());
                    response.addCookie(cookie);
                    return;
                }

            }
        }
    }


}
